<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: UserMan.php 468 2011-01-25 17:25:12Z steen.rabol $
 *
 */

Prado::using('Application.Common.Data.PortalUserRecord');

class UserMan extends PortalAdminPage
{
	private $_usersortorder		= "id";
	private $_usersortdirection	= "desc";
	private $_filter			= null;

	public function getUserSortOrder()
	{
		return $this->_usersortorder;
	}

	public function setUserSortOrder($value)
	{
		$this->_usersortorder = TPropertyValue::ensureString($value);
	}

	public function getUserSortDirection()
	{
		return $this->_usersortdirection;
	}

	public function setUserSortDirection($value)
	{
		$this->_usersortdirection = TPropertyValue::ensureString($value);
	}

	public function getDataItemCount($filter)
	{
		if($filter !== null)
		{
			$sql = "select * from tblusers $filter";
		}
		else
		{
			$sql = "select * from tblusers";
		}

		$dr = $this->DataAccess->createCommand($sql)->query();
		return $dr->RowCount;
	}

	public function dataBind($filter = null)
	{
		$offset	= $this->UserGrid->CurrentPageIndex * $this->UserGrid->PageSize;
        $limit	= $this->UserGrid->PageSize;

		if($filter !== null)
		{
			$sql = "select * from tblusers $filter ORDER BY {$this->UserSortOrder} {$this->UserSortDirection} limit $offset,$limit";
		}
		else
		{
			$sql = "select * from tblusers ORDER BY {$this->UserSortOrder} {$this->UserSortDirection} limit $offset,$limit";
		}

		try
		{
			$dr	= $this->DataAccess->createCommand($sql)->query();
			$this->UserGrid->VirtualItemCount	= $this->getDataItemCount($filter);
			$this->UserGrid->DataSource	= $dr;
			$this->UserGrid->dataBind();
		}
		catch(Exception $e)
		{
			$this->reportError(1,$e->getMessage());
		}
	}

	public function onLoad($param)
	{
		parent::onLoad($param);

		$this->setAdminPageTitle('Users');

		if($this->Request['filter'] !== null && !empty($this->Request['filter']))
		{
			$this->_filter	= "where name like '%" . $this->Request['filter'] . "%'";
			$this->_filter	.= " or ";
			$this->_filter	.= "full_name like '%" . $this->Request['filter'] . "%'";
			$this->_filter	.= " or ";
			$this->_filter	.= "email like '%" . $this->Request['filter'] . "%'";
		}

		if(!$this->isPostBack)
		{
			$this->dataBind($this->_filter);
		}
	}

	public function changePage($sender, $param)
	{
		$this->UserGrid->EditItemIndex		= -1;
		$this->UserGrid->SelectedItemIndex	= -1;
		$this->UserGrid->CurrentPageIndex	= $param->NewPageIndex;
		$this->dataBind($this->_filter);
	}

	public function pagerCreated($sender, $param)
	{
		$param->Pager->Controls->insertAt(0, 'Page: ');
	}

	public function editItem($sender, $param)
	{
		$this->UserGrid->EditItemIndex = $param->Item->ItemIndex;
		$this->dataBind($this->_filter);
	}

	public function SearchString($sender, $param)
	{
		if($this->IsValid)
		{
			$this->gotoPage('Admin.UserMan',array("filter" => $this->ttbSearchValue->Text));
		}
	}

	public function ClearSearchString($sender, $param)
	{
		$this->gotoPage('Admin.UserMan',array());
	}

	public function saveItem($sender, $param)
	{
		$item					= $param->Item;
		$userID					= $this->UserGrid->DataKeys[$item->ItemIndex];
		$userRecord				= $this->DataAccess->createCommand("select * from tblusers where id = $userID")->queryRow();
		$userRecord['role']		= TPropertyValue::ensureInteger($item->Cells[2]->UserRole->SelectedValue);
		$userRecord['sitenews']	= TPropertyValue::ensureInteger($item->Cells[3]->SiteNews->Checked);
		$userRecord['status']	= TPropertyValue::ensureInteger($item->Cells[4]->UserStatus->SelectedValue);
		$sql = "update tblusers set role=" . $userRecord['role'] . ",status=" . $userRecord['status'] . ",full_name='" . $item->FullName->TextBox->Text . "',email='" . $item->Email->TextBox->Text . "',sitenews='" . $userRecord['sitenews'] . "' where id=" . $userRecord['id'];
		$this->DataAccess->createCommand($sql)->execute();
		$this->gotoPage('Admin.UserMan');
	}

	public function itemCreated($sender, $param)
	{
		$item = $param->Item;

		if($item->ItemType === 'EditItem')
		{
			// set column width of textboxes
			$item->Email->TextBox->Columns = 40;
		}

		if($item->ItemType === 'Item' || $item->ItemType === 'AlternatingItem' || $item->ItemType === 'EditItem')
		{
			// add an aleart dialog to delete buttons
			$item->DeleteColumn->Button->Attributes->onclick = "if(!confirm('" . Prado::localize("Are you sure?")."')) return false;";
		}
	}

	public function deleteItem($sender, $param)
	{
		$this->DataAccess->createCommand("delete from tblusers where id = {$this->UserGrid->DataKeys[$param->Item->ItemIndex]}")->execute();
		$this->gotoPage('Admin.UserMan');
	}

	public function cancelItem($sender, $param)
	{
		$this->gotoPage('Admin.UserMan');
	}

	public function RoleName($p_role)
	{
		return $this->DataAccess->createCommand("select name from tblroles where id = $p_role")->queryScalar();
	}

	public function StatusName($p_status)
	{
		switch($p_status)
		{
			case 0: return Prado::localize("Normal"); break;
			case 1: return Prado::localize("Disabled"); break;
			case 2: return Prado::localize("Pending"); break;
		}
	}

	public function getUserRoles()
	{
		return $this->DataAccess->createCommand("select * from tblroles")->query();
	}

	public function ValidateUserRole($role)
	{
		$retval		= ' ';
		$first		= true;
		$validroles	= $this->getUserRoles();

		if($validroles)
		{
			foreach($validroles as $vvalue)
			{
				if($first)
				{
					$retval = $vvalue['id']; //In case we don't find our wanted we return a valid on :-)
					$first = false;
				}

				if($vvalue['id'] == $role)
				{
					return $role;
				}
			}
		}

		return $retval;
	}

	public function sortDataGrid($sender, $param)
	{
		$sortorder		= $this->getViewState("ugsortorder", '');
		$sortdirection	= $this->getViewState("ugsortdirection", '');

		if($sortorder == '' || $sortorder != $param->SortExpression)
			$sortdirection = "desc";

		if($sortorder == $param->SortExpression)
		{
			if($sortdirection == "desc")
			{
				$sortdirection = "asc";
			}
			else if($sortdirection == "asc")
			{
				$sortdirection = "desc";
			}
		}

		$this->setViewState("ugsortorder", $param->SortExpression);
		$this->setViewState("ugsortdirection", $sortdirection);

		$this->UserSortOrder		= $param->SortExpression;
		$this->UserSortDirection	= $sortdirection;

		$this->dataBind($this->_filter);
	}

	protected function sortData($data, $key)
	{
		$compare = create_function('$a,$b', 'if ($a["'.$key.'"] == $b["'.$key.'"]) {return 0;}else {return ($a["'.$key.'"] > $b["'.$key.'"]) ? 1 : -1;}');
		usort($data, $compare);
		return $data;
	}

	public function getUserStatus()
	{
		$ret	= array();
		$ret[]	= array("name" => Prado::localize("Normal"), "id" => 0);
		$ret[]	= array("name" => Prado::localize("Disabled"), "id" => 1);
		$ret[]	= array("name" => Prado::localize("Pending"), "id" => 2);
		return $ret;
	}

	public function getUserCount()
	{
		return $this->DbConnection->createCommand("select count(id) as users from tblusers")->queryScalar();
	}

	public function getGroupingText()
	{
		return Prado::localize("Users") . " (" . $this->UserCount . ")";
	}

	public function sendpassword($sender, $param)
	{

		$data = PortalUserRecord::finder()->findByid($this->UserGrid->DataKeys[$param->Item->ItemIndex]);
		if($data && ($data instanceof PortalUserRecord))
		{
			/*
			$to      = $data->email;
			$password = PortalUtil::MakePassword();
			$subject = 'New Password for: ' . $this->Application->Parameters['SiteTitle'];
			$message = "Hello " . $data->name . "\r\n" . "Here is your new password: " . $password;
			$headers = 'From: ' . $this->Application->Parameters['AdminEmail'] . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();

			if(mail($data->email,$subject,$message))
			{
				$data->password	= hash("sha256",$password);
				$data->save();
			}
			*/


			$email		= $data->email;
			$site		= $this->Application->Parameters['SiteTitle'];
			$pasword	= PortalUtil::MakePassword();
			$username	= $data->name;

			Prado::using('Application.Common.XMimeMail');
			$xMail = new XMimeMail();
			$xMail->setCharset('iso-8859-1');
			$xMail->setHtmlBody("Here is your infomation on $site<br>Username: $username<br>Password: $pasword",'');
			
 			$params['html_encoding'] = 'quoted-printable';
			$params['text_encoding'] = 'quoted-printable';
			$params['text_wrap'] = 998;
			$xMail->prepare($params);
			try
			{
				$xMail->send($data->full_name, $data->email, $site, $this->Application->Parameters['AdminEmail'], "Your information on $site");
				$data->password	= hash("sha256",$password);
				$data->save();
			}
			catch(Exception $e) { }
		}
		$this->gotoPage('Admin.UserMan');
	}

	public function onItemCommand($sender, $param)
	{
		switch($param->CommandName)
		{
			case 'sendpassword': $this->sendpassword($sender, $param); break;
		}
	}
}
?>